<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }">班级管理</el-breadcrumb-item>
      <el-breadcrumb-item>班级学员</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <!-- 班级的列表 -->
    <el-row :gutter="10">
      <!--    班级列表操作按钮    -->
      <el-col :span="10" >
        <el-card class="box-card" style="width: 100%">
          <div class="grid-content bg-purple">所有班级
            <div style="float: right ">
              <el-button type="primary" icon="el-icon-plus" circle size="mini"
                         @click="addNewClass = true"></el-button>
              <el-button type="info" icon="el-icon-edit" circle size="mini"
                         @click="openUpdateClass()"></el-button>
              <el-button type="danger" icon="el-icon-delete" circle size="mini"
                         @click="deleteClass()"></el-button>
            </div>
          </div><br>
          <!--  班级列表-->
          <template>
            <el-table :data="classData"
                      highlight-current-row
                      @current-change="loadStudentList"
                      style="width: 100%" size="small">
              <el-table-column type="index" label="序号" align="center"></el-table-column>
              <el-table-column prop="className" label="班级" align="center"></el-table-column>
              <el-table-column prop="teacherName" label="项目老师" align="center"></el-table-column>
            </el-table>
          </template>
        </el-card>
      </el-col>

      <el-col :span="7">
        <el-card class="box-card" style="width: 100%">
          <div class="grid-content bg-purple-light">班级学员
            <div style="float: right ">
              <el-button type="primary" icon="el-icon-plus" circle size="mini"
                         @click="openAddNewStudent()"></el-button>
              <el-button type="info" icon="el-icon-edit" circle size="mini"
                         @click="openHandleStudent()"></el-button>
            </div>
          </div><br>
          <!--  分组列表-->
          <template>
            <el-table :data="studentData"
                      highlight-current-row
                      @current-change="studentHighlight"
                      style="width: 100%" size="small">
              <el-table-column type="index" label="序号" align="center"></el-table-column>
              <el-table-column prop="nickname" label="学员" align="right"></el-table-column>
            </el-table>
          </template>
        </el-card>
      </el-col>

      <el-col :span="7">
        <el-card class="box-card" style="width: 100%">
          <div class="grid-content bg-purple">老师管理
            <div style="float: right ">
              <el-button type="primary" icon="el-icon-plus" circle size="mini"
                         @click="openAddNewTeacher()"></el-button>
            </div>
          </div><br>
          <!--  老师列表-->
          <template>
            <el-table :data="teachers"
                      style="width: 100%" size="small">
              <el-table-column type="index" label="序号" align="center"></el-table-column>
              <el-table-column prop="nickname" label="老师" align="right"></el-table-column>
            </el-table>
          </template>
        </el-card>
      </el-col>
    </el-row>

    <!-- 弹出的添加班级的对话框 -->
    <el-dialog title="添加班级" :visible.sync="addNewClass">
      <el-form :model="classForm">
        <el-form-item label="班级名称" >
          <el-input v-model="classForm.className"></el-input>
        </el-form-item>
        <el-form-item label="班级老师" prop="teachers" >
          <el-select v-model="teacher" value-key="id" placeholder="请选择">
            <el-option
                v-for="item in teachers"
                :key="item.id"
                :label="item.nickname"
                :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addNewClass = false">取 消</el-button>
        <el-button type="primary" @click="classAddNew()">添 加</el-button>
      </div>
    </el-dialog>

    <!-- 弹出的修改班级的对话框 -->
    <el-dialog title="修改班级" :visible.sync="updateClass">
      <el-form :model="classUpdateFrom">
        <el-form-item label="班级名称" >
          <el-input v-model="classUpdateFrom.className"></el-input>
        </el-form-item>
        <el-form-item label="班级老师" prop="teachers" >
          <el-select v-model="teacher" value-key="id" placeholder="请选择">
            <el-option
                v-for="item in teachers"
                :key="item.id"
                :label="item.nickname"
                :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateClass = false">取 消</el-button>
        <el-button type="primary" @click="classUpdate()">修改</el-button>
      </div>
    </el-dialog>

    <!-- 弹出的添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addNewUser">
      <el-form :model="userForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="userForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="userForm.description"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addNewStudent = false">取 消</el-button>
        <el-button type="primary" @click="userAddNew()">添 加</el-button>
      </div>
    </el-dialog>

    <!-- 弹出的调整学员班级的对话框 -->
    <el-dialog title="调整学员班级" :visible.sync="updateStudentClass">
      <el-form :model="studentClassUpdateFrom">
        <el-form-item label= "学员名字:" >{{highlightStudent.nickname}}
        </el-form-item>
        <el-form-item label="新班级" prop="teachers" >
          <el-select v-model="classes" value-key="id" placeholder="请选择">
            <el-option
                v-for="item in classData"
                :key="item.id"
                :label="item.className"
                :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateStudentClass = false">取 消</el-button>
        <el-button type="primary" @click="studentClassUpdate()">修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      classes: {},
      teacher: {},
      teachers: [],
      addNewClass: false,
      updateClass: false,
      addNewUser: false,
      updateStudentClass: false,
      classStandardForm: {
        className: '',
        teacherId: '',
        teacherName: ''
      },
      classForm: {
        className: '',
        teacherId: '',
        teacherName: ''
      },
      userStandardForm: {
        username: '',
        password: '',
        nickname: '',
        avatar: '',
        phone: '',
        email: '',
        classId: '',
        className: '',
        description: '',
        isTeacher: '',
        enable: ''
      },
      userForm: {
        username: '',
        password: '',
        nickname: '',
        avatar: '',
        phone: '',
        email: '',
        classId: '',
        className: '',
        description: '',
        isTeacher: '',
        enable: ''
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 4, max: 15, message: '长度在 4 到 15 个字符', trigger: 'blur'}
        ],
        nickname: [
          {required: true, message: '请输入昵称', trigger: 'blur'},
          {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入手机号码', trigger: 'blur'},
          {min: 8, max: 15, message: '长度在 8 到 15 个字符', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入电子邮箱', trigger: 'blur'},
          {min: 4, max: 30, message: '长度在 4 到 30 个字符', trigger: 'blur'}
        ]
      },
      lightClass: false,
      lightStudent: false,
      highlightClass: {},
      highlightStudent: {},
      classUpdateStandardFrom: {
        id: '',
        className: '',
        teacherId: '',
        teacherName: ''
      },
      classUpdateFrom: {
        id: '',
        className: '',
        teacherId: '',
        teacherName: ''
      },
      studentClassUpdateFrom: {
        classId: '',
        className: ''
      },
      studentClassUpdateStandardFrom: {
        classId: '',
        className: ''
      },
      classData: [],
      studentData: [],
    }
  },
  methods: {
    loadClassList(){
      let url = 'http://localhost:9878/classes';
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        if ( responseBody.state != 2000){
          this.$message.error('班级列表加载失败，请稍后再试！！')
        } else {
          this.classData = responseBody.data;
          this.highlightClass = null;
        }
      });
      this.highlightClass = {};
      this.lightClass = false;
    },
    loadTeacherList(){
      let url = 'http://localhost:9878/users/list-by-teacher';
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        if ( responseBody.state != 2000){
          this.$message.error(responseBody.message)
        } else {
          this.teachers = responseBody.data;
        }
      });
    },
    loadStudentList(classes){
      this.highlightClass=classes;
      this.lightClass = true;
      this.highlightStudent = {};
      this.lightStudent = false;
      let url = 'http://localhost:9878/users/'+classes.id+'/list-by-class';
      console.log(classes);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        if ( responseBody.state != 2000){
          this.$message.error('班级列表加载失败，请稍后再试！！')
        } else {
          this.studentData = responseBody.data;
        }
      });
    },
    classAddNew(){
      this.classForm.teacherId = this.teacher.id;
      this.classForm.teacherName = this.teacher.nickname;
      let url = 'http://localhost:9878/classes/add-new'
      console.log("班级信息为: ")
      console.log(this.classForm)
      let formData = this.qs.stringify(this.classForm, {arrayFormat: 'repeat'});
      console.log('formData = ' + formData);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url, formData).then((response) => {
        let responseBody = response.data;
        if (responseBody.state != 2000) {
          this.$message.error(responseBody.message)
        } else {
          this.$message({
            message: '添加班级成功！',
            type: 'success'
          });
        }
      });
      this.addNewClass = false;
      this.classForm = this.classStandardForm;
      this.loadMyClassList();
    },
    deleteClass(){
      if (this.highlightClass == null) {
        this.$message.error('请选择需要删除的班级！');
      } else {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let url = 'http://localhost:9878/classes/' + this.highlightClass.id + '/delete';
          console.log('url = ' + url);
          this.axios.post(url).then((response) => {
            let responseBody = response.data;
            if (responseBody.state != 2000) {
              this.$message.error(responseBody.message);
            }
            if (responseBody.state == 2000 || responseBody.state == 4040) {
              this.loadMyClassList();
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            }
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    },
    openUpdateClass(){
      if (!this.lightClass) {
        this.$message.error('请选择需要修改的班级！');
      } else {
        this.updateClass = true;
        let url = 'http://localhost:9878/classes/' + this.highlightClass.id + '/get';
        console.log('url = ' + url);
        this.axios.post(url).then((response) => {
          let responseBody = response.data;
          if (responseBody.state != 2000) {
            this.$message.error('获取班级信息失败，稍后再试！');
          }
          if (responseBody.state == 2000) {
            this.classUpdateFrom=responseBody.data;
          }
        });
        this.teacher = null;
      }
    },
    classUpdate(){
      if (this.teacher == null) {
        this.$message.error('请选择班级老师！')
      } else {
        this.classUpdateFrom.teacherId = this.teacher.id;
        this.classUpdateFrom.teacherName = this.teacher.nickname;
        let url = 'http://localhost:9878/classes/update'
        console.log("班级信息为: ")
        console.log(this.classUpdateFrom)
        let formData = this.qs.stringify(this.classUpdateFrom, {arrayFormat: 'repeat'});
        console.log('formData = ' + formData);
        this.axios
            .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
            .post(url, formData).then((response) => {
          let responseBody = response.data;
          if (responseBody.state != 2000) {
            this.$message.error(responseBody.message)
          } else {
            this.$message({
              message: '修改班级成功！',
              type: 'success'
            });
          }
        });
        this.classUpdateFrom = this.classUpdateStandardFrom;
        this.updateClass = false;
        this.loadMyClassList();
      }
    },
    openAddNewStudent(){
      if (this.highlightClass == null) {
        this.$message.error('请先选择学员的班级！');
      } else {
        this.addNewUser = true;
        this.userForm.classId = this.highlightClass.id;
        this.userForm.className = this.highlightClass.className;
        this.userForm.isTeacher = 0;
        this.userForm.enable = 1;
      }
    },
    openAddNewTeacher(){
      this.addNewUser = true;
      this.userForm.isTeacher = 1;
      this.userForm.enable = 1;
    },
    userAddNew(){
      let url = 'http://localhost:9878/users/add-new'
      console.log('用户信息');
      console.log(this.userForm)
      let formData = this.qs.stringify(this.userForm, {arrayFormat: 'repeat'});
      console.log('formData = ' + formData);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url, formData).then((response) => {
        let responseBody = response.data;
        if (responseBody.state != 2000) {
          this.$message.error(responseBody.message)
        } else {
          this.$message({
            message: '添加用户成功！',
            type: 'success'
          });
        }
        this.userForm = this.userStandardForm;
      });
      this.addNewUser = false;
      this.loadTeacherList();
      this.loadStudentList();
    },
    studentHighlight(currentRow){
      this.highlightStudent = currentRow;
      this.lightStudent = true;
    },
    openHandleStudent(){
      if (!this.lightStudent) {
        this.$message.error('请选择需要修改班级的学员！');
      } else {
        this.updateStudentClass = true;
      }
    },
    studentClassUpdate(){
      this.studentClassUpdateFrom.classId = this.classes.id;
      this.studentClassUpdateFrom.className = this.classes.className;
      let studentId = this.highlightStudent.id;
      let url = 'http://localhost:9878/users/'+studentId+'/update';
      let formData = this.qs.stringify(this.studentClassUpdateFrom, {arrayFormat: 'repeat'});
      console.log('formData = ' + formData);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url, formData).then((response) => {
        let responseBody = response.data;
        if (responseBody.state != 2000) {
          this.$message.error(responseBody.message)
        } else {
          this.$message({
            message: '修改学员班级成功！',
            type: 'success'
          });
        }
      });
      this.studentClassUpdateFrom = this.studentClassUpdateStandardFrom;
      this.highlightStudent = {};
      this.lightStudent = false;
    },
  },
  mounted() {
    this.loadClassList();
    this.loadTeacherList();
  }
}
</script>

<style scoped>
.box-card {
  width: 480px;
  height: 750px;
}
</style>